package com.woniuxy.main.handler;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;

import com.woniuxy.main.pojo.Follow;

import com.woniuxy.main.pojo.Coach;

import com.woniuxy.main.pojo.User;
import com.woniuxy.main.service.CoachService;
import com.woniuxy.main.service.GymService;
import com.woniuxy.main.service.LessonService;
import com.woniuxy.main.service.StudentService;
import com.woniuxy.main.service.UserService;
import com.woniuxy.main.util.MailUtil;
import com.woniuxy.main.util.MyUtil;
import com.woniuxy.main.util.SessionUtil;
import lombok.Data;

@Controller
@RequestMapping("/user")
@Scope("prototype")
@Data
public class UserHandler {
	@Autowired
	private UserService userService;
	@Autowired
	private CoachService coachService;
	@Autowired
	private LessonService lessonService;
	@Autowired
	private StudentService studentService;
	@Autowired
	private GymService gymService;
	private static String code;
	
	//拒绝申诉请求
	@RequestMapping("/refuseComplain")
	@ResponseBody
	public String refuseComplain(int cpid){
		String result="操作失败！";
		int row=userService.refuseComplain(cpid);
		if(row!=0){
			result="操作成功！";
		}
		return result;
	}
	
	//封禁账户
	@RequestMapping("/lockUser")
	@ResponseBody
	public String lockUser(int uid,String lockReason){
		String result="操作失败！";
		Map<String,Object> request=new HashMap<>();
		request.put("uid", uid);
		request.put("lockReason", lockReason);
		int row=userService.lockAccount(request);
		if(row!=0){
			result="操作成功！";
		}
		return result;
	}
	
	//解除账户封禁
	@RequestMapping("/unLockUser")
	@ResponseBody
	public String unLockUser(int uid,int cpid){
		//System.out.println("cpid:"+cpid);
		String result="操作失败！";
		int row=userService.unLockAccount(uid);
		if(row!=0){
			//修改申诉表
			int row2=userService.aceptComplain(cpid);
			if(row2!=0){
				result="操作成功！";
			}
		}
		return result;
	}
	
	//管理员后台添加教练账户
	@RequestMapping("/addCoach")
	@ResponseBody
	public Map<String,String> addCoach(String cname,String cage,String csex,String uphone,String umail,String address){
		Map<String,String> info=new HashMap<>();
		//格式验证
		if(cname==null||cage==null||csex==null||uphone==null||umail==null||address==null){
			info.put("result", "非法操作！");
			return info;
		}
		int age=0;
		try {
			Integer inputAge=new Integer(cage);
			age=inputAge;
		} catch (Exception e) {
			info.put("result", "请输入正确的年龄信息！");
			return info;
		}
		if(uphone.length()!=11){
			info.put("result", "电话号码格式不正确！请输入正确的11位电话号码！");
			return info;
		}
		try {
			Long inputPhone=new Long(uphone);
		} catch (Exception e) {
			info.put("result", "电话号码格式不正确！请输入正确的11位电话号码！");
			return info;
		}
		if(!MyUtil.isEmail(umail)){
			info.put("result", "邮箱格式不正确！请输入正确的电子邮箱地址！");
			return info;
		}
		//检查手机号是否已存在
		String isPhoneExist=userService.isPhoneExist(uphone);
		if(isPhoneExist!=null){
			info.put("result", "该电话号码已注册，请尝试其他电话号码！");
			return info;
		}
		//检查邮箱是否已存在
		String isMailExist=userService.isMailExist(umail);
		if(isMailExist!=null){
			info.put("result", "该邮箱已注册，请尝试其他邮箱！");
			return info;
		}
		//如果以上信息都正确，则开始添加账户
		info.put("result", "添加账户失败！");
		String account=MyUtil.randomAccount();
		ByteSource salt =ByteSource.Util.bytes(account);
		//初始密码123456
		String pwd=new SimpleHash("MD5","123456",salt,1024).toString();
		//插入user表
		User user=new User();
		user.setAccount(account);
		user.setAddress(address);
		user.setHeadImage("滑稽.png");
		user.setNickName(account);
		user.setPwd(pwd);
		user.setUserRole("coach");
		user.setUphone(uphone);
		user.setUmail(umail);
		int row1=userService.adminAddCoach(user);
		if(row1!=0){
			//System.out.println(user.getUid());
			//插入教练表
			Coach coach=new Coach();
			coach.setUid(user.getUid());
			coach.setCname(cname);
			coach.setCage(age);
			coach.setCsex(csex);
			coach.setPublicLevel(0);
			int row2=coachService.adminAdd(coach);
			if(row2!=0){
				info.put("result", "添加账户成功！");
				info.put("account", account);
			}
		}
		return info;
	}

	//发送邮件
	@RequestMapping("/sendMail")
	@ResponseBody
	public void register(String mail){
		int number = (int) (Math.random()*9000+1000);				
		Session session=SessionUtil.getSession();
		//把验证码存入session
		session.setAttribute("number", number);
		try {
			//发送邮件
			MailUtil.sendMail(mail,"YOGA注册", "这里是您的注册验证码:"+number);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	//随机获得一个账号
	public String judgeAccount(){
		String account =null;
		boolean flag=true;
		while(flag){
		int i =(int)(Math.random()*900000+100000);
		String str =""+i;
		//给一个随机账号
		 account = "woniuYOGA"+str;
		//判断此账户是否被占用
		User user =userService.selectByAccount(account);
		if(user==null){
			flag=false;				
			}
		}
		return account;
	}
	
	//邮件注册的方法
	@RequestMapping("/mail")
	@ResponseBody
	public String register(User user,String number){
		if(user.getUmail()==null || user.getUmail().length()==0){
			return "邮箱不能为空";
		}
		//给一个账号
		String account =judgeAccount();
		if(account!=null){
			user.setAccount(account);
		}
		Session session=SessionUtil.getSession();
		//获取验证码
		String nowNumber =""+ session.getAttribute("number");
		//获取加密的密码
		String pwd =newPwd(user);
		user.setPwd(pwd);
		//判断验证码
		if(!nowNumber.equalsIgnoreCase(number)){
			return "注册失败,验证码不正确";
		}
		//判断是否存在相同账户
			String str=userService.isMailExist(user.getUmail());
			if(str==null){
			userService.addUserByMail(user);
			if(user.getUserRole()!=null){
		if(user.getUserRole().equals("coach")){
			//查询注册的用户
			User u=userService.selectByMail(user.getUmail());
			//根据身份 给其创建一个只有uid信息
			coachService.insertCoach(u.getUid());
			//创建课程表同时创建其课程表
			Coach c=coachService.selectByUid(u.getUid());
			lessonService.insertLesson(c.getCid());
		}	
		if(user.getUserRole().equals("student")){
			//查询注册的用户
			User u=userService.selectByMail(user.getUmail());
			//根据身份 给其创建一个只有uid信息
			studentService.insertStudent(u.getUid());
		}
		if(user.getUserRole().equals("gym")){
			//查询注册的用户
			User u=userService.selectByMail(user.getUmail());
			//根据身份 给其创建一个只有uid信息
			gymService.insertGym(u.getUid());
		}	
			}
			return "注册成功";
			}
		return "注册失败,用户已存在";		
	}
	
	//手机注册的方法
	@RequestMapping("/creatYZM")
	@ResponseBody
	public void creatYZM(HttpServletRequest request,String phoneNum){
		
		getPhonemsg(phoneNum);
		HttpSession session =request.getSession();
		session.setAttribute("yzm", code);
	}
	
	@RequestMapping("/confirmYZM")
	@ResponseBody
	public String yzyzm(HttpServletRequest request,String sryzm,User user){
       String result="失败";
       if(user.getUphone()==null || user.getUphone().length()==0){
			return "手机号不能为空";
		}
		String account =judgeAccount();
		if(account!=null){
			user.setAccount(account);
		}
		//获取加密的密码
		String pwd =newPwd(user);
		user.setPwd(pwd);
		//获取验证码
		HttpSession session =request.getSession();
		String yzm =(String)session.getAttribute("yzm");
		if(!sryzm.equalsIgnoreCase(yzm)){
			result="验证码不正确,注册失败";
		}
		//判断是否有相同手机号
		String str =userService.isPhoneExist(user.getUphone());
		if(str==null){
			userService.addUserByPhone(user);
			if(user.getUserRole()!=null){
			if(user.getUserRole().equals("coach")){
				//查询注册的用户
				User u=userService.selectByPhone(user.getUphone());
				//根据身份 给其创建一个只有uid信息
				coachService.insertCoach(u.getUid());
				//创建课程表同时创建其课程表
				Coach c=coachService.selectByUid(u.getUid());
				lessonService.insertLesson(c.getCid());
			}
			if(user.getUserRole().equals("student")){
				//查询注册的用户
				User u=userService.selectByPhone(user.getUphone());

				//根据身份 给其创建一个只有uid信息
				studentService.insertStudent(u.getUid());
			}

			if(user.getUserRole().equals("gym")){
				//查询注册的用户
				User u=userService.selectByPhone(user.getUphone());
				//根据身份 给其创建一个只有uid信息
				gymService.insertGym(u.getUid());
			}			
}
			}
			result="成功";
			return result;
		}
	
	
	
	//普通注册的方法
	@RequestMapping("/register")
	@ResponseBody
	public String addUserByAccount(HttpServletRequest request,User user,String loginImgCode){
		if(user.getAccount()==null || user.getAccount().length()==0){
			return "账号不能为空";
		}
		//获取加密的密码
		String pwd =newPwd(user);
		user.setPwd(pwd);		
		//获取session
		HttpSession session =request.getSession();
		//获取图形验证码		
		String codeVal = session.getAttribute("loginCode").toString();
		if(!codeVal.equalsIgnoreCase(loginImgCode)){
			return "注册失败,验证码不正确";
		}
		//验证账号是否重复
		String str = userService.isAccountExist(user.getAccount());
		if(str==null){
			userService.addUserByAccount(user);
			//为教练创建其应有的表
			if(user.getUserRole()!=null){
			if(user.getUserRole().equals("coach")){
				//查询注册的用户
				User u=userService.selectByAccount(user.getAccount());
				//根据身份 给其创建一个只有uid信息
				coachService.insertCoach(u.getUid());
				//创建课程表同时创建其课程表
				Coach c=coachService.selectByUid(u.getUid());
				lessonService.insertLesson(c.getCid());
			}
			if(user.getUserRole().equals("student")){
				//查询注册的用户
				User u=userService.selectByAccount(user.getAccount());
				//根据身份 给其创建一个只有uid信息
				studentService.insertStudent(u.getUid());
			}

			if(user.getUserRole().equals("gym")){
				//查询注册的用户
				User u=userService.selectByAccount(user.getAccount());
				//根据身份 给其创建一个只有uid信息
				gymService.insertGym(u.getUid());
			}			
		}
			return "注册成功";
		}
		return "注册失败";
	}
	
	//密码加密的方法
	public String newPwd(User user){
		//System.out.println("传入的账号："+user.getAccount());
		//System.out.println("传入的密码："+user.getPwd());
		ByteSource	salt =ByteSource.Util.bytes(user.getAccount());
		String newPwd=new SimpleHash("MD5",user.getPwd(),salt,1024).toString();
		return newPwd;
	}
	
	//登录的方法
	@RequestMapping("/loginByAccount")
	@ResponseBody
	public Map<String,String> login(HttpServletRequest request,User user,String loginImgCode){
		Map<String,String> info=new HashMap<>();
		//获取session
		HttpSession session =request.getSession();
		//在httpsession中存入uid
		Session sion= SessionUtil.getSession();
		//获取图形验证码		
		String codeVal = session.getAttribute("loginCode").toString();
		if(!codeVal.equalsIgnoreCase(loginImgCode)){
			info.put("result", "登录失败,验证码不正确");
			return info;
		}
		//传入加密的密码
		String newPass = newPwd(user);
		user.setPwd(newPass);
		System.out.println("mima:"+newPass);
		//获取subject对象
		Subject curruentUser = SecurityUtils.getSubject();
		User findUser=userService.selectByAccount(user.getAccount());
		//判断当前用户是否已经验证
		if(!curruentUser.isAuthenticated()){
			//进行验证
			UsernamePasswordToken token=new UsernamePasswordToken(user.getAccount(),user.getPwd());
			System.out.println("认证中");
			try {
				session.setAttribute("uid", sion.getAttribute("uid"));
				session.setAttribute("address", sion.getAttribute("address"));
				session.setAttribute("userRole", sion.getAttribute("userRole"));
				curruentUser.login(token);
				System.out.println("认证成功");
				session.setAttribute("uid", sion.getAttribute("uid"));
				session.setAttribute("address", sion.getAttribute("address"));
				session.setAttribute("userRole", sion.getAttribute("userRole"));
				info.put("result", "登录成功");
				//查询用户角色
				info.put("role", findUser.getUserRole());
				session.setAttribute("uid", sion.getAttribute("uid"));
				session.setAttribute("address", sion.getAttribute("address"));
				session.setAttribute("userRole", sion.getAttribute("userRole"));
				if(null==findUser.getAddress()||"".equals(findUser.getAddress())){
					info.put("Mes1", "noAdd");
				}else{
					info.put("Mes1", "hasAdd");
				}
				if(findUser.getIsLock()==0){
					info.put("Mes2", "noLock");
				}else{
					info.put("Mes2", findUser.getLockReason());
				}
				return info;
			} catch (UnknownAccountException e) {
				//System.out.println("用户不存在");
				//返回登录页面
				info.put("result", "登录失败,账号或密码不正确");
				return info;
			}catch(IncorrectCredentialsException e){
				//System.out.println("密码不对");
				info.put("result", "登录失败,密码不正确");
				return info;				
			}
		}else{
			info.put("result", "登录成功");
			info.put("role", findUser.getUserRole());
			if(null==findUser.getAddress()||"".equals(findUser.getAddress())){
				info.put("Mes1", "noAdd");
			}else{
				info.put("Mes1", "hasAdd");
			}
			if(findUser.getIsLock()==0){
				info.put("Mes2", "noLock");
			}else{
				info.put("Mes2", findUser.getLockReason());
			}
		}
		return info;
	}
	//手机登录
	@RequestMapping("/loginByPhone")
	@ResponseBody
	public Map<String,String> loginByPhone(HttpServletRequest request,User user,String loginImgCode){
		Map<String,String> info=new HashMap<>();
		//获取session
		HttpSession session =request.getSession();
		//获取图形验证码		
		String codeVal = session.getAttribute("loginCode").toString();
		//在httpsession中存入uid
		Session sion= SessionUtil.getSession();
		if(!codeVal.equalsIgnoreCase(loginImgCode)){
			info.put("result", "登录失败,验证码不正确");
			return info;
		}
		//根据手机查用户
		User user1=userService.selectByPhone(user.getUphone());
		//传入加密的密码
		ByteSource	salt =ByteSource.Util.bytes(user1.getAccount());
		String newPwd=new SimpleHash("MD5",user.getPwd(),salt,1024).toString();
		user.setPwd(newPwd);
	/*	System.out.println("这里是加密的-----"+user.getPwd());*/
		//获取subject对象
		Subject curruentUser = SecurityUtils.getSubject();
		//判断当前用户是否已经验证
		if(!curruentUser.isAuthenticated()){
			//进行验证
			UsernamePasswordToken token=new UsernamePasswordToken(user.getUphone(),user.getPwd());
			System.out.println("认证中"+token);
			try {
				curruentUser.login(token);
				//System.out.println("认证成功");
				info.put("role", user1.getUserRole());
				session.setAttribute("uid", sion.getAttribute("uid"));
				session.setAttribute("address", sion.getAttribute("address"));
				session.setAttribute("userRole", sion.getAttribute("userRole"));
				if(null==user1.getAddress()||"".equals(user1.getAddress())){
					info.put("Mes1", "noAdd");
				}else{
					info.put("Mes1", "hasAdd");
				}
				if(user1.getIsLock()==0){
					info.put("Mes2", "noLock");
				}else{
					info.put("Mes2", user1.getLockReason());
				}
				info.put("result", "登录成功");
				return info;
			} catch (UnknownAccountException e) {
				//System.out.println("用户不存在");
				//返回登录页面
				info.put("result", "登录失败,账号或密码不正确");
				return info;
			}catch(IncorrectCredentialsException e){
				//System.out.println("密码不对");
				info.put("result", "登录失败,账号或密码不正确");
				return info;				
			}
		}else{
			info.put("result", "登录成功");
			info.put("role", user1.getUserRole());
			if(null==user1.getAddress()||"".equals(user1.getAddress())){
				info.put("Mes1", "noAdd");
			}else{
				info.put("Mes1", "hasAdd");
			}
			if(user1.getIsLock()==0){
				info.put("Mes2", "noLock");
			}else{
				info.put("Mes2", user1.getLockReason());
			}
		}
		return info;
	}
	//邮箱登录
	@RequestMapping("/loginByMail")
	@ResponseBody
	public Map<String,String> loginByMail(HttpServletRequest request,User user,String loginImgCode){
		Map<String,String> info=new HashMap<>();
		//System.out.println("User:---"+user);
		//获取session
		HttpSession session =request.getSession();
		//获取图形验证码		
		String codeVal = session.getAttribute("loginCode").toString();
		//在httpsession中存入uid
		Session sion= SessionUtil.getSession();
		if(!codeVal.equalsIgnoreCase(loginImgCode)){
			info.put("result", "登录失败,验证码不正确");
			return info;
		}
		//根据邮箱差用户
		User user1 = userService.selectByMail(user.getUmail());
		//传入加密的密码

		ByteSource	salt =ByteSource.Util.bytes(user1.getAccount());
		String newPwd=new SimpleHash("MD5",user.getPwd(),salt,1024).toString();
		user.setPwd(newPwd);
		//System.out.println("这里是加密的-----"+user.getPwd());

		//获取subject对象
		Subject curruentUser = SecurityUtils.getSubject();
		//判断当前用户是否已经验证
		if(!curruentUser.isAuthenticated()){
			//进行验证
			UsernamePasswordToken token=new UsernamePasswordToken(user.getUmail(),user.getPwd());
			System.out.println("认证中"+token);
			try {
				curruentUser.login(token);
				//System.out.println("认证成功");
				info.put("role", user1.getUserRole());
				session.setAttribute("uid", sion.getAttribute("uid"));
				session.setAttribute("address", sion.getAttribute("address"));
				session.setAttribute("userRole", sion.getAttribute("userRole"));
				if(null==user1.getAddress()||"".equals(user1.getAddress())){
					info.put("Mes1", "noAdd");
				}else{
					info.put("Mes1", "hasAdd");
				}
				if(user1.getIsLock()==0){
					info.put("Mes2", "noLock");
				}else{
					info.put("Mes2", user1.getLockReason());
				}
				info.put("result", "登录成功");
				return info;
			} catch (UnknownAccountException e) {
				//System.out.println("用户不存在");
				//返回登录页面
				info.put("result", "用户不存在");
				return info;
			}catch(IncorrectCredentialsException e){
				//System.out.println("密码不对");
				info.put("result", "登录失败,密码不对");
				return info;				
			}
		}else{
			info.put("result", "登录成功");
			info.put("role", user1.getUserRole());
			if(null==user1.getAddress()||"".equals(user1.getAddress())){
				info.put("Mes1", "noAdd");
			}else{
				info.put("Mes1", "hasAdd");
			}
			if(user1.getIsLock()==0){
				info.put("Mes2", "noLock");
			}else{
				info.put("Mes2", user1.getLockReason());
			}
		}
		return info;
	}
	
	//根据uid查询user信息
	@RequestMapping("/findUserByUid")
	@ResponseBody
	public User findUserByUid(int uid){
		User user=userService.selectByUid(uid);
		return user;
	}	
	    //上传头像图片
		@RequestMapping("/head")
		@ResponseBody
		public String upload(HttpServletRequest request, @RequestParam("headImage") MultipartFile file)
				throws IllegalStateException, IOException {
			// 得到该工程目录在硬盘上的绝对路径
			String realPath = request.getSession().getServletContext().getRealPath("");
			// 测试该路径
			// 将该图片写入文件流
			File images = new File(realPath, "images");
			if (!images.exists()) {
				images.mkdirs();// 创建文件夹
			}

			String fileName = file.getOriginalFilename();

			// 生成新文件名
			String newName = UUID.randomUUID().toString();

			// 得到文件后缀名
			String type = fileName.substring(fileName.lastIndexOf("."));

			newName += type;

			// 拼接新文件的路径
			File uploadFile = new File(images, newName);

			// 将文件保存到服务器本地
			file.transferTo(uploadFile);

			// 服务器路径
			String viturlPath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
					+ request.getContextPath() + "/";
			//得到该图片的网络的绝对路径
			String netPath=viturlPath + "images/" + newName;
			//得到该图片的项目的绝对路径
			String jobPath="/images/" + newName;
			
			// 将图片的路径保存至数据库
			
			/*int uid=(int)request.getSession().getAttribute("uid");*/
			int uid=(int)SessionUtil.getSession().getAttribute("uid");
			
			User user =new User();
			user.setUid(uid);
		    user.setHeadImage(newName);	
		    userService.addUserHeadImage(user);
			
			// 返回该图片的项目的绝对路径,作用于前台显示
			return jobPath;
		}	
	
	
	
	/**
	 * 阿里云短信服务配置
	 * 
	 * @param mobile
	 * @return
	 */
	public static String getPhonemsg(String mobile) {

		/**
		 * 进行正则关系校验
		 */
		System.out.println(mobile);
		if (mobile == null || mobile == "") {
			System.out.println("手机号为空");
			return "";
		}
		/**
		 * 短信验证---阿里大于工具
		 */

		// 设置超时时间-可自行调整
		System.setProperty(StaticPeram.defaultConnectTimeout, StaticPeram.Timeout);
		System.setProperty(StaticPeram.defaultReadTimeout, StaticPeram.Timeout);
		// 初始化ascClient需要的几个参数
		final String product = StaticPeram.product;// 短信API产品名称（短信产品名固定，无需修改）
		final String domain = StaticPeram.domain;// 短信API产品域名（接口地址固定，无需修改）
		// 替换成你的AK
		final String accessKeyId = StaticPeram.accessKeyId;// 你的accessKeyId,参考本文档步骤2
		final String accessKeySecret = StaticPeram.accessKeySecret;// 你的accessKeySecret，参考本文档步骤2
		// 初始化ascClient,暂时不支持多region
		IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
		try {
			DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
		} catch (ClientException e1) {
			e1.printStackTrace();
		}

		// 获取验证码
		code = vcode();

		IAcsClient acsClient = new DefaultAcsClient(profile);
		// 组装请求对象
		SendSmsRequest request = new SendSmsRequest();
		// 使用post提交
		request.setMethod(MethodType.POST);
		// 必填:待发送手机号。支持以逗号分隔的形式进行批量调用，批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
		request.setPhoneNumbers(mobile);
		// 必填:短信签名-可在短信控制台中找到
		request.setSignName(StaticPeram.SignName);
		// 必填:短信模板-可在短信控制台中找到
		request.setTemplateCode(StaticPeram.TemplateCode);
		// 可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
		// 友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败
		request.setTemplateParam("{ \"code\":\"" + code + "\"}");
		// 可选-上行短信扩展码(无特殊需求用户请忽略此字段)
		// request.setSmsUpExtendCode("90997");
		// 可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
		request.setOutId("yourOutId");
		// 请求失败这里会抛ClientException异常
		SendSmsResponse sendSmsResponse;
		try {
			sendSmsResponse = acsClient.getAcsResponse(request);
			if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
				// 请求成功
				System.out.println("获取验证码成功！！！");
			} else {
				// 如果验证码出错，会输出错误码告诉你具体原因
				System.out.println(sendSmsResponse.getCode());
				System.out.println("获取验证码失败...");
			}
		} catch (ServerException e) {
			e.printStackTrace();
			return "由于系统维护，暂时无法注册！！！";
		} catch (ClientException e) {
			e.printStackTrace();
			return "由于系统维护，暂时无法注册！！！";
		}
		return "true";
	}

	/**
	 * 生成6位随机数验证码
	 * 
	 * @return
	 */
	public static String vcode() {
		String vcode = "";
		for (int i = 0; i < 6; i++) {
			vcode = vcode + (int) (Math.random() * 9);
		}
		return vcode;
	}
	
	/**
	 * 查询当前用户关注的人--关注
	 */
	@RequestMapping("/allFollowed")
	@ResponseBody
	public List<User> findFollowed(int currentUid){
		currentUid = (int) SessionUtil.getSession().getAttribute("uid");
		return userService.findFollowed(currentUid);
	}
	/**
	 * 查询关注当前用户的人--粉丝
	 */
	@RequestMapping("/allFans")
	@ResponseBody
	public List<User> findFans(int currentUid){
		currentUid = (int) SessionUtil.getSession().getAttribute("uid");
		return userService.findFans(currentUid);
	}
	/**
	 * 查询和当前用户相互关注的人--好友
	 */
	@RequestMapping("/allFriend")
	@ResponseBody
	public List<User> findFriend(int currentUid){
		currentUid = (int) SessionUtil.getSession().getAttribute("uid");
		return userService.findFriend(currentUid);
	}
	/**
	 * 取消关注
	 */
	@RequestMapping("/cancleFollow")
	@ResponseBody
	public String cancleFollow(int currentUid,int follower){
		currentUid = (int) SessionUtil.getSession().getAttribute("uid");
		String result = "取消失败";
		Follow follow = new Follow();
		follow.setUid(currentUid);
		follow.setTargetUid(follower);
		if (userService.cancleFollow(follow)!=0) {
			result = "取消成功";
		}
		return result;
	}
	/**
	 * 新增关注
	 * param:当前登录用户id(currentUid)，关注对象用户id(follower)
	 */
	@RequestMapping("/addFollow")
	@ResponseBody
	public String addFollow(int currentUid,int follower){
		currentUid = (int) SessionUtil.getSession().getAttribute("uid");
		String result = "关注失败";
		Follow follow = new Follow();
		follow.setUid(currentUid);
		follow.setTargetUid(follower);
		if(userService.checkFollow(follow)!=null){
			result = "操作失败，你已关注ta";
		}else if (userService.addFollow(follow)!=0) {
			result = "关注成功";
		}
		return result;
	}
	/**
	 * 判断和用户之间关系
	 */
	@RequestMapping("/judgeRelation")
	@ResponseBody
	public String judgeRelation(int currentUid,int follower){
		currentUid = (int) SessionUtil.getSession().getAttribute("uid");
		String result = "未关注";
		Follow follow = new Follow();
		follow.setUid(currentUid);
		follow.setTargetUid(follower);
		if (userService.checkFollow(follow)!=null) {
			result = "互相关注";
		}
		return result;
	}

	//用户补充手机、邮箱信息
	@RequestMapping("/updateUserByphone")
	@ResponseBody
	public String updateUserByPhone(HttpServletRequest request,User user,String nowCode){
		//获取uid
			Session session = SessionUtil.getSession();
		String str = (String) session.getAttribute("uid");
		int uid = Integer.parseInt(str);
		user.setUid(uid);
		
	     if(user.getUphone()==null || user.getUphone().length()==0){
	    	 return "手机号不能为空";
		}
		//获取验证码
		HttpSession session1 =request.getSession();
		String yzm =(String)session1.getAttribute("yzm");
		if(!yzm.equals(nowCode)){
			return "验证码不正确";
		}
		System.out.println("更新:"+user);
		int row=userService.updateUser(user);
		if(row==1){
			return "绑定成功";
		}
		return "绑定失败";
	}
	@RequestMapping("/updateUserByMail")
	@ResponseBody
	public String updateUserByMail(User user,String code){
		//获取uid
		Session session = SessionUtil.getSession();
		String str = (String) session.getAttribute("uid");
		int uid = Integer.parseInt(str);
		user.setUid(uid);
		//调用邮箱验证码
		String nowNumber =""+ session.getAttribute("number");
		if(!nowNumber.equals(code)){
			return "验证码不正确";
		}
		int row=userService.updateUser(user);
		if(row==1){
			return "绑定成功";
		}
		return "绑定失败";
	}
	//上传地址
	@RequestMapping("/address")
	@ResponseBody
	public String updateAddress(User user){
		int row=userService.updateUser(user);
		if(row==1){
			return "添加成功";
		}
		return "添加失败";
	}
	//获取用户对象
	@RequestMapping("/userMessage")
	@ResponseBody
	public User userMessage(){
		Object obj =SessionUtil.getSession().getAttribute("uid");
		int uid=(int)obj;
		
		User user = userService.selectByUid(uid);
		return user;
	}
	//更改密码
	//更改密码前 根据验证码判断手机号 或邮箱
	@ResponseBody
	@RequestMapping("/judgeCode")
	public String judgeCode(HttpServletRequest request, String code,User user){
		//如果是通过手机改密码
		if(user.getUphone()!=null && user.getUphone().length()!=0){
		//判断手机号是否存在
		String str = userService.isPhoneExist(user.getUphone());
		if(str==null){
			return "不存在此手机号";
		}
		//获取验证码
		HttpSession session =request.getSession();
		String loginCode =(String)session.getAttribute("yzm");
		if(!code.equalsIgnoreCase(loginCode)){
			return "验证码不正确";
			}
		}
		//如果是通过邮箱更改密码
		if(user.getUmail()!=null && user.getUmail().length()!=0){
			//判断邮箱是否存在
			String s =userService.isMailExist(user.getUmail());
			if(s==null){
				return "邮箱不存在";
			}
			//获取验证码
			HttpSession session =request.getSession();
			String loginCode =(String)session.getAttribute("number");
			if(!code.equalsIgnoreCase(loginCode)){
				return "验证码不正确";
				}
		}

		return "验证成功";
	}
	//手机更改密码
	@ResponseBody
	@RequestMapping("/changePwdByPhone")
	public String changPwd(String uphone,String pwd){
		//根据手机号码查询该对象
		User user = userService.selectByPhone(uphone);
		ByteSource	salt =ByteSource.Util.bytes(user.getAccount());
		String newPwd=new SimpleHash("MD5",pwd,salt,1024).toString();
		userService.changePwd(newPwd, user.getUid());
		return "修改成功";
	}
	//邮箱更改密码
	@RequestMapping("/changePwdByMail")
	@ResponseBody
	public String changPwdByMail(String mail,String pwd){
		//根据邮箱差对象
		User user=userService.selectByMail(mail);
		ByteSource	salt =ByteSource.Util.bytes(user.getAccount());
		String newPwd=new SimpleHash("MD5",pwd,salt,1024).toString();
		userService.changePwd(newPwd, user.getUid());
		return "修改成功";
	}
}
